# frozen_string_literal: true

class ApplicationController < ActionController::Base
  wechat_api
  protect_from_forgery with: :exception
  before_action :get_info

  def get_info
    wechat_oauth2 do |openid|
      # openid = "oguIZuKJxnjbA0ZXImy-pAxOhIkI"
      @current_user = User.find_by(open_id: openid)
      unless @current_user
        user_info = Wechat.api.user(openid)
        user = User.new
        user.open_id = openid
        user.nickname = user_info['nickname']
        user.country = user_info['country']
        user.province = user_info['province']
        user.city = user_info['city']
        user.subscribe_time = user_info['subscribe_time']
        user.headimgurl = user_info['headimgurl']
        user.save
        @current_user = user
      end
      session['user_id'] = @current_user.id
      unless @current_user.activated
        redirect_to users_url, notice: '请先注册成会员！' unless request.path.starts_with?('/users')
      end
    end
  end
end
